package com.ophiux.wechat.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ophiux.wechat.db.MchAppModel;
import com.ophiux.wechat.db.Mch_App_Map;
import com.ophiux.wechat.utils.StringUtil;
import com.ophiux.wechat.utils.WeChatPayUtil;

/**
 * 授权回调地址
 * @author chenh
 */
@SuppressWarnings("serial")
public class RedirectServlet extends HttpServlet{
	private static Logger logger = LoggerFactory.getLogger(RedirectServlet.class);

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("gb2312");
		logger.info("微信授权回调-进入回调");
		String code = request.getParameter("code");
		String token = request.getParameter("token");
		MchAppModel mchApp = Mch_App_Map.getMchAppModelByMchId(token);
		String appid="";
		String appsecret ="";
		if(!StringUtil.isEmpty(token)) {
			appid = mchApp.getAppid();
			appsecret = mchApp.getAppsecret();
		}else {
			appid = request.getParameter("appid");
			appsecret = request.getParameter("appsecret");
		}
		String client_back_url = request.getParameter("client_back_url");
		
		logger.info("微信授权回调传递过来的参数："+"code="+code+";appid="+appid+";appsecret="+appsecret);
		if(StringUtil.isEmpty(code)){
			response.getWriter().write("用户拒绝授权");
		}else{
			/**
			 * 获取openId
			 */
			String openId = WeChatPayUtil.Oauth(appid, appsecret, code);
			/**
			 * 拼装重定向url
			 */
			StringBuffer sb = new StringBuffer();
			sb.append(client_back_url).append("?").append("&openId=").append(openId);
			//重定向
			logger.info("授权成功：重定向至终端："+sb.toString());
			response.sendRedirect(sb.toString());
		}
		
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
	
}
